//#include "KpExtGP.h"
//#include "fmt/core.h"
//#include "fmt/ranges.h"
//#include "fmt/color.h"
//#include "spdlog/spdlog.h"
//#include "spdlog/sinks/rotating_file_sink.h"
//#include "spdlog/sinks/stdout_color_sinks.h"

#include "kpextCommonDef.h"
#include "KpExtGP.h"


#ifdef OS_WIN
//  专门为windows 平台打开虚拟终端序列功能

#include <windows.h>
#include <fileapi.h>

#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif

bool IS_CONSOLE_SUPORT_COLOR = false;

void kpextSetWinConsoleVT100(bool on)
{
    auto h = GetStdHandle( STD_OUTPUT_HANDLE );
    if(h){
        DWORD mode = 0;
        GetConsoleMode( h, &mode );
        if(on) mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
        else mode &= static_cast<decltype (mode)>(~ENABLE_VIRTUAL_TERMINAL_PROCESSING);
        SetConsoleMode( h, mode );
        IS_CONSOLE_SUPORT_COLOR = on;
    }
}

#else

bool IS_CONSOLE_SUPORT_COLOR = true;
void kpextSetWinConsoleVT100(bool on)
{
    UNUSE_VAR(on);
}
#endif



void kpextSetLogger(const char *loggername, unsigned int sizeMB, unsigned int filecnt)
{
#ifndef KPEXT_NO_SPDLOG
    spdlog::drop(spdlog::default_logger_raw()->name());  // 先删除默认Logger
    spdlog::drop("");

    if(loggername == nullptr || loggername[0] == 0){
        spdlog::set_default_logger(spdlog::stdout_color_mt(""));  // stdout_color_mt 作为默认Logger
#ifdef OS_WIN
        kpextSetWinConsoleVT100(true);
#else
        IS_CONSOLE_SUPORT_COLOR = true;
#endif
        return;
    }

    if(sizeMB < 1) sizeMB = 1;
    if(filecnt < 1) filecnt = 1;
    spdlog::set_default_logger(
                spdlog::rotating_logger_mt(loggername,
                                           "kp_ext_log",
                                           static_cast<size_t>(1024 * 1024 * sizeMB),
                                           static_cast<size_t>(filecnt)
                                           )
                );
    IS_CONSOLE_SUPORT_COLOR = false;
#endif
}


void kpextSetLoggerLevel(int level){
#ifndef KPEXT_NO_SPDLOG
    spdlog::set_level(static_cast<spdlog::level::level_enum>(level));
#endif
}


void kpextSetLoggerPattern(const char * pattern){
#ifndef KPEXT_NO_SPDLOG
    if(! pattern) return;
    spdlog::set_pattern(pattern);
#endif
}
